package com.angel.kuaidi.activity;

import java.io.InputStream;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import com.angel.kuaidi.R;
import com.angel.kuaidi.db.DB;
import com.angel.kuaidi.entity.HistoryInfo;
import com.angel.kuaidi.entity.WuliuCompanyInfo;
import com.angel.kuaidi.net.XmlParserManager;
import com.angel.kuaidi.utils.StringUtils;
import com.angel.kuaidi.utils.Utils;
import com.angel.kuaidi.utils.UtilsLog;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.content.DialogInterface.OnKeyListener;
import android.content.Intent;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AutoCompleteTextView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;

public class IndexActivity extends BaseActivity {

	ImageView iv_down;
	TextView tv_wuliu;
	Button btn_search;
	AutoCompleteTextView et_wuliu;
	TextView tv_hot_wuliu;
	GridView gv_hotwuliu;
	GridView gv_wuliu;

	int position = -1;
	int hotposition = -1;
	private long endTime = 0;
	ArrayList<WuliuCompanyInfo> list = new ArrayList<WuliuCompanyInfo>();
	ArrayList<WuliuCompanyInfo> hotList = new ArrayList<WuliuCompanyInfo>();
	ArrayList<HistoryInfo> historys = new ArrayList<HistoryInfo>();
	GridViewAdapter adapter;
	GridViewAdapter hotadapter;
	private LayoutInflater inflater;

	Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {

			HistoryInfo hi = (HistoryInfo) msg.obj;
			if (hi != null) {
				if (!StringUtils.isNullOrEmpty(hi.chinesename)) {
					WuliuCompanyInfo wci = new WuliuCompanyInfo();
					wci.chinesename = hi.chinesename;
					wci.pinyinname = hi.pinyinname;
					mApp.setCompany(wci);

					tv_wuliu.setText(hi.chinesename);

				} else {
					tv_wuliu.setText("请选择");
				}
				if (msg.what == 0) {
					et_wuliu.setText(hi.postid);
					et_wuliu.dismissDropDown();
				}
				// et_wuliu.dismissDropDown();
			} else {
				tv_wuliu.setText("请选择");
			}

			super.handleMessage(msg);
		}

	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);

		setView(R.layout.index);
		setTitle("更多", "快递查询助手", "去扫描");

		initData();
		initView();
		registerListener();
		display();
		adView();

	}

	private void adView() {

		View v = findViewById(R.id.adview);
		SharedPreferences share = mContext.getSharedPreferences("adview_flag", Context.MODE_PRIVATE);
		if (share.getBoolean("flag", false)) {
			v.setVisibility(View.VISIBLE);
		} else {
			v.setVisibility(View.GONE);
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {

		if (keyCode == KeyEvent.KEYCODE_BACK) {
			exit();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	private void exit() {

		new AlertDialog.Builder(mContext).setTitle("退出应用").setPositiveButton("确定", new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
				finish();
			}
		}).setNegativeButton("取消", new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
			}
		}).setMessage("是否退出应用?").create().show();
	}

	private void initData() {

		inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		endTime = System.currentTimeMillis();
		// 检查更新
		checkUpdate();

		
		// 积分墙
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {

		// 创建菜单
		menu.add(Menu.NONE, Menu.FIRST + 0, 1, "历史").setIcon(android.R.drawable.ic_menu_gallery);
		menu.add(Menu.NONE, Menu.FIRST + 1, 2, "更多").setIcon(android.R.drawable.ic_menu_more);

		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {

		Intent intent = null;
		switch (item.getItemId()) {
		case Menu.FIRST:
			//
			intent = new Intent();
			intent.setClass(mContext, HistoryActivity.class);
			startActivity(intent);
			break;
		case Menu.FIRST + 1:
			//
			intent = new Intent();
			intent.setClass(mContext, MoreActivity.class);
			startActivity(intent);
			break;
		default:
			break;
		}

		return super.onOptionsItemSelected(item);
	}

	private void initView() {

		iv_down = (ImageView) findViewById(R.id.iv_down);
		tv_wuliu = (TextView) findViewById(R.id.tv_wuliu);
		btn_search = (Button) findViewById(R.id.btn_search);
		et_wuliu = (AutoCompleteTextView) findViewById(R.id.et_wuliu);
		tv_hot_wuliu = (TextView) findViewById(R.id.tv_hot_wuliu);
		gv_hotwuliu = (GridView) findViewById(R.id.gv_hotwuliu);
		gv_wuliu = (GridView) findViewById(R.id.gv_wuliu);

	}

	private void registerListener() {

		tv_wuliu.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {

			}
		});
		btn_search.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {

				String s = et_wuliu.getText().toString().trim();
				String com = tv_wuliu.getText().toString().trim();
				if (!"请选择".equals(com)) {

					if (!StringUtils.isNullOrEmpty(s)) {
						Intent intent = new Intent();
						intent.putExtra("postid", s);
						intent.putExtra("company", mApp.getCompany());
						intent.setClass(mContext, KuaidiDetailActivity.class);
						startActivity(intent);
					} else {
						Utils.toast(mContext, "运单号不能为空");
					}
				} else {
					Utils.toast(mContext, "未选择物流公司");
				}
			}
		});

		gv_wuliu.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int index, long arg3) {

				if (position != index) {

					WuliuCompanyInfo w = mApp.getCompany();
					if (w != null) {
						w.isChecked = false;
					}
					if (position != -1) {
						list.get(position).isChecked = false;
					}
					WuliuCompanyInfo wci = list.get(index);
					wci.isChecked = true;
					// 全局
					mApp.setCompany(wci);
					tv_wuliu.setText(wci.chinesename);
					position = index;
					hotposition = -1;
				}
				if (adapter != null) {
					adapter.notifyDataSetChanged();
				}
				if (hotadapter != null) {
					hotadapter.notifyDataSetChanged();
				}
			}
		});

		gv_hotwuliu.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int index, long arg3) {

				if (hotposition != index) {
					WuliuCompanyInfo w = mApp.getCompany();
					if (w != null) {
						w.isChecked = false;
					}
					if (hotposition != -1) {
						hotList.get(hotposition).isChecked = false;
					}
					WuliuCompanyInfo wci = hotList.get(index);
					wci.isChecked = true;
					// 全局
					mApp.setCompany(wci);
					tv_wuliu.setText(wci.chinesename);
					hotposition = index;
					position = -1;
				}
				if (adapter != null) {
					adapter.notifyDataSetChanged();
				}
				if (hotadapter != null) {
					hotadapter.notifyDataSetChanged();
				}
			}
		});

		et_wuliu.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
				Message msg = handler.obtainMessage();
				msg.obj = historys.get(position);
				msg.what = 1;
				handler.sendMessage(msg);
			}
		});
	}

	private void display() {

		
		hotadapter = new GridViewAdapter(hotList);
		adapter = new GridViewAdapter(list);
		new LoadDataAsy().execute();

		SimpleCursorAdapter cursorAdapter = new SimpleCursorAdapter(this, R.layout.auto_complete_textview_item, null, new String[] { "postid" }, new int[] { R.id.tv_postid }) {

			@Override
			public Cursor runQueryOnBackgroundThread(CharSequence c) {

				if (c == null || c.length() == 0) {
					// 如果输入为空，则执行父类函数
					return super.runQueryOnBackgroundThread(c);
				} else {

					long temp = Math.abs(endTime - System.currentTimeMillis());
					endTime = System.currentTimeMillis();
					if (temp < 200) {
						return null;
					}
					UtilsLog.i("msg", "db query");
					// DB.getInstance(mContext).close();
					Cursor cursor = DB.getInstance(mContext).getCursor(HistoryInfo.class, null,
							"postid like '%" + c + "%' or chinesename like '%" + c + "%' or pinyinname like '%" + c + "%' ");
					HistoryInfo hi = null;
					historys.clear();
					while (cursor.moveToNext()) {
						hi = new HistoryInfo();

						hi._id = cursor.getString(cursor.getColumnIndex("_id"));
						hi.chinesename = cursor.getString(cursor.getColumnIndex("chinesename"));
						hi.pinyinname = cursor.getString(cursor.getColumnIndex("pinyinname"));
						hi.postid = cursor.getString(cursor.getColumnIndex("postid"));

						historys.add(hi);
					}
					// 生成自定义的游标
					return cursor;
				}
			}

			@Override
			public void bindView(View view, Context context, Cursor cursor) {
				super.bindView(view, context, cursor);
				// View view =
				// inflater.inflate(R.layout.auto_complete_textview_item, null);
				TextView tv_postid = (TextView) view.findViewById(R.id.tv_postid);
				TextView tv_company = (TextView) view.findViewById(R.id.tv_company);

				tv_postid.setText(cursor.getString(cursor.getColumnIndex("postid")));
				tv_company.setText(cursor.getString(cursor.getColumnIndex("chinesename")));
			}

			@Override
			public View newView(Context context, Cursor cursor, ViewGroup parent) {

				View view = inflater.inflate(R.layout.auto_complete_textview_item, null);
				TextView tv_postid = (TextView) view.findViewById(R.id.tv_postid);
				TextView tv_company = (TextView) view.findViewById(R.id.tv_company);

				tv_postid.setText(cursor.getString(cursor.getColumnIndex("postid")));
				tv_company.setText(cursor.getString(cursor.getColumnIndex("chinesename")));

				return view;
			}

		};

		// 初始化输入框的自动适配
		et_wuliu.setThreshold(1);
		// 需要设置才能取到值
		cursorAdapter.setStringConversionColumn(3);
		et_wuliu.setAdapter(cursorAdapter);

		new Thread(new Runnable() {
			@Override
			public void run() {
				HistoryInfo hi = new HistoryInfo();
				hi = DB.getInstance(mContext).queryFirst(HistoryInfo.class);
				Message msg = handler.obtainMessage();
				msg.what = 0;
				msg.obj = hi;
				handler.sendMessage(msg);
			}
		}).start();

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		//
		if (resultCode == RESULT_OK) {
			String s = data.getStringExtra("RESULT");
			et_wuliu.setText(s);
		}
	}

	@Override
	public void onClick(View v) {
		super.onClick(v);
		switch (v.getId()) {

		default:
			break;
		}
	}

	@Override
	protected void onDestroy() {
		
		super.onDestroy();
	}

	private void freshHotWuliu() {
		//

	}

	class LoadDataAsy extends AsyncTask<Void, Void, List<WuliuCompanyInfo>> {

		Dialog dialog = null;

		@Override
		protected void onPostExecute(List<WuliuCompanyInfo> l) {

			if (dialog != null && dialog.isShowing()) {
				dialog.dismiss();
			}
			if (l != null && l.size() > 0) {

				for (int i = 0; i < l.size(); i++) {
					WuliuCompanyInfo wci = l.get(i);
					if ("1".equals(wci.ishot)) {
						hotList.add(wci);
					}
				}
				//
				l.removeAll(hotList);
				gv_hotwuliu.setAdapter(hotadapter);
				// 刷新热门物流
				freshHotWuliu();
				list.addAll(l);
				gv_wuliu.setAdapter(adapter);
				//
				hotadapter.notifyDataSetChanged();
				adapter.notifyDataSetChanged();
			} else {
				Utils.toast(mContext, "加载数据异常!");
			}
			super.onPostExecute(l);
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			dialog = Utils.showProcessDialog(mContext, "正在初始化数据...");
			dialog.setOnKeyListener(new OnKeyListener() {
				@Override
				public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
					return true;
				}
			});
		}

		@Override
		protected List<WuliuCompanyInfo> doInBackground(Void... params) {

			try {
				InputStream is = getResources().getAssets().open("company_info.xml");
				return XmlParserManager.getBeanList(is, "company", WuliuCompanyInfo.class);
			} catch (Exception e) {
				e.printStackTrace();
			}

			return null;
		}

	}

	class GridViewAdapter extends BaseAdapter {

		private ArrayList<WuliuCompanyInfo> l = null;

		public GridViewAdapter(ArrayList<WuliuCompanyInfo> list) {
			this.l = list;
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return this.l.size();
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return null;
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return 0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {

			WuliuCompanyInfo wi = this.l.get(position);
			return getView(position, convertView, parent, wi);
		}

		public View getView(int position, View convertView, ViewGroup parent, WuliuCompanyInfo w) {

			convertView = inflater.inflate(R.layout.grid_item, null);

			TextView tv = (TextView) convertView.findViewById(R.id.tv_content);

			WuliuCompanyInfo wi = w;
			tv.setText(wi.chinesename);
			if (wi.isChecked) {
				tv.setTextColor(0xffffffff);
				convertView.setBackgroundColor(0xffb4dffb);
			} else {
				convertView.setBackgroundResource(R.drawable.item_bg);
			}

			return convertView;
		}

	}

	@Override
	protected void onRightBtnClick() {
		super.onRightBtnClick();
		//
		// finish();
		Intent intent = new Intent(mContext, CaptureActivity.class);
		startActivityForResult(intent, 101);
	}

	@Override
	protected void onLeftBtnClick() {
		// super.onLeftBtnClick();
		Intent intent = new Intent(mContext, MoreActivity.class);
		startActivity(intent);
	}

}
